package com.yuandengta.yomall.seckill.scheduled;

import com.yuandengta.yomall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品定时上架 {@link SeckillSkuScheduled}
 *  每天凌晨3点，上架最近三天需要秒杀商品
 *  当天 00:00:00 - 23:59:59
 *  明天 00:00:00 - 23:59:59
 *  后天 00:00:00 - 23:59:59
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@Slf4j
@Service
public class SeckillSkuScheduled {

    private final String UPLOAD_LOCK = "seckill:upload:lock";

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 秒杀商品定时上架
     *
     * 幂等处理：
     *  - 1.分布式锁
     *  - 2.缓存数据时判断是否已经存在key
     *      - key不存在就缓存
     *      - key存在不做处理
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void uploadSeckillSkuLast3Days(){
        log.info("秒杀商品定时上架...");
        // 幂等处理，分布式锁
        // 锁的业务执行完成，状态已经更新完成，释放锁以后，其他人获取到的就是最新的状态
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuLast3Days();
        } finally {
            lock.unlock();
        }
    }
}
